﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.RBAC;
using RBAC.Api.Read.Dto;

namespace RBAC.Api.Read.CommandHandler.RBAC
{
    public class GetRoleCommandHandler : IRequestHandler<GetRoleCommand, APIResult<APIPagin<RoleDto>>>
    {
        private readonly IBaseRepositry<Role> role;
        private readonly IBaseRepositry<RolePermission> rolepermission;
        private readonly IBaseRepositry<Permission> permission;
        private readonly IMapper mapper;

        public GetRoleCommandHandler(IBaseRepositry<Role> baseRepositry,
                    IBaseRepositry<RolePermission> baseRepositry1,
                    IBaseRepositry<Permission> baseRepositry2,
                    IMapper mapper)
        {
            role = baseRepositry;
            rolepermission = baseRepositry1;
            permission = baseRepositry2;
            this.mapper = mapper;
        }
        public Task<APIResult<APIPagin<RoleDto>>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPagin<RoleDto>> result = new APIResult<APIPagin<RoleDto>>();
            result.Code = ResultCode.Success;
            result.Message = "查询成功";

            //获取角色列表
            var list = role.GetAll().AsNoTracking();
            //模糊查询
            if (!string.IsNullOrEmpty(request.RoleName))
            {
                list = list.Where(x => x.RoleName.Contains(request.RoleName));
            }

            var roleDto = mapper.Map<List<RoleDto>>(list);
            //分页
            var totalCount = list.Count();
            var page = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            roleDto = roleDto.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();


            //循环Dto，获取权限id,获取权限名称
            foreach (var item in roleDto)
            {
                //获取权限id
                //var permissionId=rolepermission.GetAll().Where(x=>x.RoleId==item.Id)
                //    .Select(x=>x.PermissionId).ToList();
                //item.PermissionId = permissionId;
                var permissionId = rolepermission.GetAll().Where(x => x.RoleId == item.Id)
                    .Select(x => x.PermissionId).ToList();
                item.PermissionId = permissionId;
                //获取权限名称
                var permissionName = permission.GetAll().Where(x => permissionId.Contains(x.Id))
                    .Select(x => x.PermissionName).ToList();

                item.PermissionName = string.Join(",", permissionName);
            }

            APIPagin<RoleDto> res = new APIPagin<RoleDto>()
            {
                TotaleCount = totalCount,
                PageCount = page,
                List = roleDto
            };
            result.Data = res;

            return Task.FromResult(result);
        }
    }
}
